package cn.pconline.autoclub.service;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Activity;
import cn.pconline.autoclub.entity.Album;
import cn.pconline.autoclub.entity.CityDyna;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubDyna;
import cn.pconline.autoclub.entity.DynaImage;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.DynaPraise;
import cn.pconline.autoclub.entity.DynaReply;
import cn.pconline.autoclub.entity.Subject;
import cn.pconline.autoclub.entity.SubjectDyna;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.entity.UserDyna;
import cn.pconline.autoclub.entity.UserPraise;
import cn.pconline.autoclub.entity.Vote;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.Regex;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.dyna.AbstractDyna;
import cn.pconline.autoclub.util.dyna.CommentDyna;
import cn.pconline.autoclub.util.dyna.PostReply;
import cn.pconline.autoclub.util.dyna.TopicDyna;
import cn.pconline.officialclub.entity.OClub;
import cn.pconline.officialclub.entity.OClubDyna;
import cn.pconline.officialclub.service.OClubService;
import cn.pconline.officialclub.service.ODynaService;
import cn.pconline.officialclub.service.OMemberService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.danga.MemCached.MemCachedClient;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.Mid;
import org.gelivable.dao.SqlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;

/**
 * 车友会动态、同城动态、用户动态
 *
 * @author <a href="mailto:chensy0203@163.com">chensy</a>
 */
public class DynaService {

    @Autowired
    private GeliOrm geliOrm;
    @Autowired
    private GeliDao geliDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PagerService pagerService;
    @Autowired
    private UserService userService;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private ClubService clubService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private SendMsgService sendMsgService;
    @Autowired
    private PromotionService promotionService;
    @Autowired
    private OClubService oClubService;
    @Autowired
    private ODynaService oDynaService;
    @Autowired
    private OMemberService oMemberService;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private SubjectDynaService subjectDynaService;
    @Autowired
    private UserSubjectService userSubjectService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private VoteService voteService;
    @Autowired
    private DynaIndexService dynaIndexService;
    @Autowired
    private AlbumService albumService;
    @Autowired
    protected MemCachedClient mcc;
    public static final String DYNA_MC_KEY = "DynaInfo-DynaImage-";
    public static final int MAX_PICTURE_NUM = 9;
    public static final int STRING_LENGTH_300 = 300;//字符串长度
    public static final int DEFAULT_AUTHORPHOTO_SIZE = 50;//作者头像50X50
    public static final int ORDER_POST_DATE = 1; //回复时间排序
    private static final Logger log = LoggerFactory.getLogger(DynaService.class);

    /**
     * 清缓存
     *
     * @param dynaInfoId
     * @return
     */
    public boolean deleteDynaCache(long dynaInfoId) {
        return mcc.delete(DYNA_MC_KEY + dynaInfoId);
    }

    /**
     * 统一使用这个方法更新DynaInfo，会手工操作MC
     *
     * @param info
     * @return
     */
    public int updateDyna(DynaInfo info) {
        return updateDyna(info, null);
    }

    /**
     * 统一使用这个方法更新DynaInfo，会手工操作MC
     *
     * @param info
     * @param field
     * @return
     */
    public int updateDyna(DynaInfo info, String field) {
        int update;
        if (field == null || field.length() == 0) {
            update = geliDao.update(info);
        } else {
            update = geliDao.update(info, field);
        }
        if (update > 0) {
            deleteDynaCache(info.getDynaInfoId());
        }
        return update;
    }

    /**
     * 创建车友会动态的索引记录
     *
     * @param dynaInfo
     * @return
     */
    public long createClubDyna(DynaInfo dynaInfo) {
        ClubDyna dyna = new ClubDyna();
        dyna.setClubId(dynaInfo.getClubId());
        dyna.setCreateAt(dynaInfo.getCreateAt());
        dyna.setCreateDate(dynaInfo.getCreateDate());
        dyna.setDynaInfoId(dynaInfo.getDynaInfoId());
        dyna.setForumId(dynaInfo.getForumId());
        dyna.setLastPostAt(dynaInfo.getLastPostAt());
        dyna.setPick(dynaInfo.getPick());
        dyna.setPostCount(dynaInfo.getPostCount());
        dyna.setRecommend(dynaInfo.getRecommend());
        dyna.setStatus(dynaInfo.getStatus());
        dyna.setType(dynaInfo.getType());
        dyna.setCreateBy(dynaInfo.getCreateBy());
        return geliDao.create(dyna);
    }

    /**
     * 创建用户动态的索引记录
     *
     * @param dynaInfo
     * @return
     */
    public long createUserDyna(DynaInfo dynaInfo) {
        UserDyna dyna = new UserDyna();
        dyna.setUserId(dynaInfo.getCreateBy());
        dyna.setCreateAt(dynaInfo.getCreateAt());
        dyna.setCreateDate(dynaInfo.getCreateDate());
        dyna.setDynaInfoId(dynaInfo.getDynaInfoId());
        dyna.setForumId(dynaInfo.getForumId());
        dyna.setLastPostAt(dynaInfo.getLastPostAt());
        dyna.setPick(dynaInfo.getPick());
        dyna.setPostCount(dynaInfo.getPostCount());
        dyna.setRecommend(dynaInfo.getRecommend());
        dyna.setStatus(dynaInfo.getStatus());
        dyna.setType(dynaInfo.getType());
        return geliDao.create(dyna);
    }

    /**
     * 创建同城动态的索引记录
     *
     * @param dynaInfo
     * @return
     */
    private long createCityDyna(DynaInfo dynaInfo) {
        CityDyna dyna = new CityDyna();
        dyna.setCreateBy(dynaInfo.getCreateBy());
        dyna.setCreateAt(dynaInfo.getCreateAt());
        dyna.setCreateDate(dynaInfo.getCreateDate());
        dyna.setDynaInfoId(dynaInfo.getDynaInfoId());
        dyna.setForumId(dynaInfo.getForumId());
        dyna.setLastPostAt(dynaInfo.getLastPostAt());
        dyna.setPick(dynaInfo.getPick());
        dyna.setPostCount(dynaInfo.getPostCount());
        dyna.setRecommend(dynaInfo.getRecommend());
        dyna.setStatus(dynaInfo.getStatus());
        dyna.setType(dynaInfo.getType());
        dyna.setProvinceId(dynaInfo.getProvinceId());
        dyna.setCityId(dynaInfo.getCityId());
        return geliDao.create(dyna);
    }

    /**
     * 仅给createTopicDyna方法调用
     *
     * @param info
     * @param topic
     */
    private void setDynaInfo(DynaInfo info, TopicDyna topic) {
        info.setClubId(topic.getClubId());
        info.setContent(topic.getMessage());
        info.setCreateDate(topic.getCreateDate());
        info.setCreateName(topic.getCreateName());
        info.setForumId(topic.getForumId());
        info.setForumName(topic.getForumName());
        info.setLastPostAt(topic.getLastPostAt());
        info.setLastPostBy(topic.getLastPostBy());
        info.setLastPostName(topic.getLastPostName());
        info.setPetrol(topic.getPetrol());
        info.setPick(topic.getPick());
        info.setPostCount(topic.getPostCount());
        info.setRecommend(topic.getRecommend());
        info.setTitle(topic.getTopicTitle());
        info.setTopicId(topic.getTopicId());
        info.setCreateBy(topic.getUserId());
        info.setProvinceId(topic.getProvinceId());
        info.setCityId(topic.getCityId());
        if (topic.isQuestionTopic()) {//是否是提问帖
            info.setType(DynaInfo.TYPE_QUESTION);
        } else {
            info.setType(DynaInfo.TYPE_TOPIC);
        }
        info.setTargetId(topic.getTopicId());
    }

    /**
     * 创建动态（论坛帖子） 给论坛同步发帖，同步精华帖 调用
     *
     * @param topic
     * @param images 如果没有图片就传空的
     * @return
     */
    public long createTopicDyna(TopicDyna topic, List<DynaImage> images) {
        DynaInfo isExistInfo = findDynaInfoByTopicId(topic.getTopicId(), topic.getCreateDate());
        if (isExistInfo == null) {//如果不存在此帖子才创建新的
            DynaInfo info = new DynaInfo();
            setDynaInfo(info, topic);
            info.setCensored(DynaInfo.CENSORED_UNDO);
            boolean hasPic = (images != null && !images.isEmpty());
            info.setIsPic(hasPic ? DynaInfo.PIC_IS : DynaInfo.PIC_NOT);
            info.setStatus(DynaInfo.STATUS_NORMAL);
            //更新相关字段默认跟创建相关字段一致
            info.setUpdateAt(topic.getCreateDate());
            info.setUpdateBy(topic.getUserId());
            if (topic.getProvinceId() <= 0 && topic.getCityId() <= 0) {
                long userId = info.getCreateBy();
                User user = userService.findUser(userId);
                if (user != null && user.getJoinedClubCount() > 0) {
                    info.setProvinceId(user.getProvinceId());
                    if (promotionService.isMunicipality(user.getProvinceId())) {
                        info.setCityId(0);
                    } else {
                        info.setCityId(user.getCityId());
                    }
                }
            }
            info.setCreateAt(DateUtils.getNow());
            info.setAppTitle(topic.getAppTitle());
            long infoId = geliDao.create(info);
            if (infoId == 0) {
                log.error("插入动态记录失败！createTopicDyna");
                return infoId;
            }
            if (hasPic) {
                for (DynaImage image : images) {
                    image.setDynaInfoId(infoId);
                    geliDao.create(image);
                }
            }
            if (topic.getClubId() > 0) {
                //创建车友会动态索引
                createClubDyna(info);
                sendClubDynaMsg(info);
            }
            if (info.getProvinceId() > 0 || info.getCityId() > 0) {
                //创建同城动态索引
                createCityDyna(info);
            }
            //创建用户动态索引
            createUserDyna(info);
            //创建官方车友会动态索引
            createOClubDyna(info);

            //动态发送到bip(个人中心使用)
            sendDynaWithUc(infoId, info.getCreateDate());
            //创建动态索引
            dynaIndexService.createDynaIndex(info);
            return infoId;
        } else {
            //帖子动态相关的信息，应该都是以传参的为准，查数据库得到的都是以前旧数据，可能会有问题
            //1.clubId为0的问题
            //2.如果是同步精华帖操作，不需要再增加油值，油值应该为0，以传入的参数为准，查数据库得到的petrol可能是以前的加精操作增加的油值
            //3.用户退出车友会后，修改了昵称、内容等信息，这时再加入车友会，应该是重新设置，而不是直接查数据库的旧数据
            setDynaInfo(isExistInfo, topic);
            updateDyna(isExistInfo);
            int clubDynaCount = rollbackClubDyna(isExistInfo.getClubId(), isExistInfo.getDynaInfoId());
            if (clubDynaCount == 0) {//不存在
                createClubDyna(isExistInfo);
            }
            //创建官方车友会动态
            List<OClub> oClubs = oClubService.queryClubBy(isExistInfo.getCreateBy(), isExistInfo.getForumId());
            if (oClubs != null && !oClubs.isEmpty()) {
                for (OClub oClub : oClubs) {
                    int oClubDynaCount = oDynaService.rollbackClubDyna(oClub.getoClubId(), isExistInfo.getDynaInfoId());
                    if (oClubDynaCount == 0) {
                        //创建官方车友会动态索引
                        createOClubDyna(isExistInfo);
                    }
                }
            }
            long userDynaCount = rollbackUserDyna(isExistInfo.getCreateBy(), isExistInfo.getDynaInfoId());
            if (userDynaCount == 0) {
                createUserDyna(isExistInfo);
            }
            if (isExistInfo.getProvinceId() > 0 || isExistInfo.getCityId() > 0) {
                long cityDynaCount = rollbackCityDyna(isExistInfo.getProvinceId(), isExistInfo.getCityId(), isExistInfo.getDynaInfoId());
                if (cityDynaCount == 0) {
                    createCityDyna(isExistInfo);
                }
            }
            return isExistInfo.getDynaInfoId();
        }
    }

    /**
     * 创建动态（车友会留言）
     *
     * @param comment
     * @param images 如果没有图片就传空的
     * @return
     */
    public DynaInfo createCommentDyna(CommentDyna comment, List<DynaImage> images) {
        DynaInfo info = new DynaInfo();
        info.setCensored(DynaInfo.CENSORED_UNDO);
        info.setFromType(comment.getFromType());
        info.setClubId(comment.getClubId());
        info.setContent(comment.getContent());
        info.setCreateDate(comment.getCreateDate());
        info.setCreateName(comment.getCreateName());
        //第一次发表留言动态，上次回复人是自己
        info.setLastPostAt(comment.getCreateDate());
        info.setLastPostBy(comment.getCreateBy());
        info.setProvinceId(comment.getProvinceId());
        info.setCityId(comment.getCityId());
        info.setLastPostName(comment.getCreateName());
        info.setPostCount(0);
        info.setUpdateAt(comment.getUpdateDate());
        boolean hasPic = (images != null && !images.isEmpty());
        info.setIsPic(hasPic ? DynaInfo.PIC_IS : DynaInfo.PIC_NOT);
        info.setStatus(DynaInfo.STATUS_NORMAL);
        info.setType(DynaInfo.TYPE_COMMENT);
        info.setCreateBy(comment.getCreateBy());
        info.setProvinceId(comment.getProvinceId());
        info.setCityId(comment.getCityId());
        long infoId = geliDao.create(info);
        if (infoId == 0) {
            log.error("插入动态记录失败！createCommentDyna");
            return null;
        }
        if (hasPic) {
            for (DynaImage image : images) {
                image.setDynaInfoId(infoId);
                geliDao.create(image);
            }
        }
        if (comment.getClubId() > 0) {
            //创建车友会动态索引
            createClubDyna(info);
            sendClubDynaMsg(info);
        }
        if (comment.getProvinceId() > 0 || comment.getCityId() > 0) {
            //创建同城动态索引
            createCityDyna(info);
        }
        //创建话题相关索引
        //根据说说内容，创建或参与话题,并记录说说参考过的话题ID
        String subjectIds = createSubjectByDyna(info);
        if (StringUtils.isNotEmpty(subjectIds)) {
            info.setSubjectIds(subjectIds);
            updateDyna(info, "subject_ids");
        }
        //创建用户动态索引
        createUserDyna(info);
        //创建动态索引
        dynaIndexService.createDynaIndex(info);
        //动态发送到bip(个人中心使用)
        sendDynaWithUc(infoId, comment.getCreateDate());
        return info;
    }

    /**
     * 同步论坛的帖子回复，提供给同步论坛帖子的接口调用，同步精华帖时也需要同步回复
     *
     * @param dynaInfoId
     * @param dynaInfoCreateDate
     * @param floor
     * @param createDate
     * @param createName
     * @param content
     * @return
     */
    public DynaReply replyTopicDyna(PostReply post) {
        DynaReply replyTo = null;
        DynaInfo info = null;
        if (post.getPostToPostId() > 0) {//引用楼层
            replyTo = findDynaReplyBy(post.getTopicId(), post.getTopicCreateAt(), post.getPostToPostId());
            if (replyTo == null) {
                return null;
            }
        } else {//不引用楼层
            info = findDynaInfoByTopicId(post.getTopicId(), post.getTopicCreateAt());
            if (info == null) {
                return null;
            }
        }
        DynaReply reply = new DynaReply();
        reply.setCensored(DynaReply.CENSORED_UNDO);
        reply.setTopicId(post.getTopicId());
        reply.setPostId(post.getPostId());
        reply.setFloor(post.getFloor());
        reply.setCreateDate(post.getCreateAt());
        reply.setCreateBy(post.getUserId());
        reply.setCreateName(post.getCreateName());
        reply.setContent(post.getMessage());
        reply.setType(DynaReply.TYPE_TOPIC);
        reply.setStatus(DynaReply.STATUS_NORMAL);
        reply.setIsPic(DynaReply.PIC_NOT);//目前默认没有图片
        if (info != null) {
            reply.setDynaInfoId(info.getDynaInfoId());
        }
        if (replyTo != null) {
            reply.setDynaInfoId(replyTo.getDynaInfoId());
            reply.setPostToDynaReplyId(replyTo.getDynaReplyId());
            reply.setPostToPostId(post.getPostToPostId());
            reply.setPostToNickName(post.getPostToNickName());
            reply.setPostToUserId(post.getPostToUserId());
            reply.setPostToFloor(post.getPostToFloor());
        }
        long replyId = geliDao.create(reply);
        if (replyId > 0) {
            return reply;
        } else {
            return null;
        }
    }

    /**
     * 创建动态回复
     *
     * @param reply
     * @return
     */
    public long replyCommentDyna(DynaReply reply) {
        reply.setCensored(DynaReply.CENSORED_UNDO);
        reply.setCreateDate(new Date());
        reply.setIsPic(DynaReply.PIC_NOT);//目前默认没有图片
        reply.setStatus(DynaReply.STATUS_NORMAL);
        reply.setType(DynaReply.TYPE_COMMENT);
        return geliDao.create(reply);
    }

    /**
     * 更新最后回复人相关信息，回复总数加1
     *
     * @param dynaInfoId
     * @param coubId
     * @param dynaInfoCreateDate
     * @param userId
     * @param postName
     * @param postAt
     * @return
     */
    public boolean updateLastReplyInfo(
            long dynaInfoId, long coubId, Date dynaInfoCreateDate,
            long userId, String postName, Date postAt) {
        DynaInfo info = findDynaInfoById(dynaInfoId, dynaInfoCreateDate);
        if (info == null) {
            return false;
        }
        info.setPostCount(info.getPostCount() + 1);
        info.setLastPostAt(postAt);
        info.setLastPostBy(userId);
        info.setLastPostName(postName);
        return updateLastReplyInfo(info);
    }

    /**
     * 修改索引表和info表相关的最后回复人信息
     *
     * @param info
     * @return
     */
    private boolean updateLastReplyInfo(DynaInfo info) {
        ClubDyna dyna = findClubDynaById(info.getDynaInfoId(), info.getClubId());
        if (dyna != null) {
            dyna.setPostCount(info.getPostCount());
            dyna.setLastPostAt(info.getLastPostAt());
            geliDao.update(dyna, "post_count,last_post_at");
        }
        //更新品牌车友会动态分表
        List<OClub> oClubs = oClubService.queryClubBy(info.getCreateBy(), info.getForumId());
        if (oClubs != null && !oClubs.isEmpty()) {
            for (OClub oClub : oClubs) {
                OClubDyna oClubDyna = oDynaService.findClubDyna(info.getDynaInfoId(), oClub.getoClubId());
                if (oClubDyna != null) {
                    oClubDyna.setPostCount(info.getPostCount());
                    oClubDyna.setLastPostAt(info.getLastPostAt());
                    geliDao.update(oClubDyna, "post_count,last_post_at");
                }
            }
        }
        UserDyna userDyna = findUserDynaById(info.getDynaInfoId(), info.getCreateBy());
        if (userDyna != null) {
            userDyna.setPostCount(info.getPostCount());
            userDyna.setLastPostAt(info.getLastPostAt());
            geliDao.update(userDyna, "post_count,last_post_at");
        }
        CityDyna cityDyna = findCityDynaById(info.getDynaInfoId(), info.getProvinceId(), info.getCityId());
        if (cityDyna != null) {
            cityDyna.setPostCount(info.getPostCount());
            cityDyna.setLastPostAt(info.getLastPostAt());
            geliDao.update(cityDyna, "post_count,last_post_at");
        }
        return updateDyna(info, "post_count,last_post_at,last_post_by,last_post_name") > 0;
    }

    /**
     * 根据动态ID修改动态内容
     *
     * @param dynaInfoId
     * @param createDate
     * @return
     */
    public long updateDynaInfo(TopicDyna topicDyna, List<DynaImage> dynaImages) {
        DynaInfo dynaInfo = findDynaInfoByTopicId(topicDyna.getTopicId(), topicDyna.getCreateDate());
        if (dynaInfo != null) {
            dynaInfo.setTitle(topicDyna.getTopicTitle());
            dynaInfo.setContent(topicDyna.getMessage());
            dynaInfo.setUpdateAt(new Date());
            dynaInfo.setUpdateBy(topicDyna.getUserId());
            if (dynaImages != null && !dynaImages.isEmpty()) {
                dynaInfo.setIsPic(DynaInfo.PIC_IS);
            } else {
                dynaInfo.setIsPic(DynaInfo.PIC_NOT);
            }
            //如果之前的apptitle不为空，则修改
            String appTitle = dynaInfo.getAppTitle();
            if(!StringUtils.isBlank(appTitle)){
            	dynaInfo.setAppTitle(topicDyna.getTopicTitle());
            }

            long update = updateDyna(dynaInfo, "title,content,updateAt,updateBy,isPic");
            if (update == 0L) {
                log.error("更新动态记录失败！updateDynaInfo");
                return update;
            }

            //将原来旧的图片删除
            deleteDynaImage(dynaInfo.getDynaInfoId());
            //插入新的图片
            if (dynaImages != null && !dynaImages.isEmpty()) {
                for (DynaImage dynaImage : dynaImages) {
                    dynaImage.setDynaInfoId(dynaInfo.getDynaInfoId());
                    geliDao.create(dynaImage);
                }
            }
            return update;
        }
        return 0;
    }

    /**
     * 根据dynaInfoId删除所有的图片
     *
     * @param dynaInfoId
     */
    public void deleteDynaImage(long dynaInfoId) {
        List<DynaImage> dynaImages = getImagesByDynaInfoId(dynaInfoId, 0);
        for (DynaImage dynaImage : dynaImages) {
            geliDao.delete(dynaImage, dynaImage.getImageId());
        }
    }

    /**
     * 逻辑删除动态回复
     *
     * @param id
     * @param dynaInfoId
     * @param createDate 这个是动态info的createDate
     * @return
     */
    public long deleteDynaReply(long id, long dynaInfoId, Date createDate) {
        try {
            DynaReply reply = geliDao.find(DynaReply.class, dynaInfoId, id);
            reply.setStatus(DynaReply.STATUS_DELETE);
            return geliDao.update(reply, "status");
        } catch (EmptyResultDataAccessException e) {
            return 0;
        }
    }

    /**
     * 修改动态的内容的审核状态
     *
     * @param dynaInfoId
     * @param createDate
     * @param censored
     * @return
     */
    public long censorDynaInfo(DynaInfo info, int censored) {
        if (info == null) {
            return 0;
        }
        ClubDyna clubDyna = findClubDynaById(info.getDynaInfoId(), info.getClubId());
        UserDyna userDyna = findUserDynaById(info.getDynaInfoId(), info.getCreateBy());
        CityDyna cityDyna = findCityDynaById(info.getDynaInfoId(), info.getProvinceId(), info.getCityId());
        int status = censored == DynaInfo.CENSORED_PASS ? DynaInfo.STATUS_NORMAL : DynaInfo.STATUS_DELETE;
        if (clubDyna != null && status == DynaInfo.STATUS_DELETE) {
            clubDyna.setStatus(status);
            geliDao.update(clubDyna);
        }
        if (userDyna != null && status == DynaInfo.STATUS_DELETE) {
            userDyna.setStatus(status);
            geliDao.update(userDyna);
        }
        if (cityDyna != null && status == DynaInfo.STATUS_DELETE) {
            cityDyna.setStatus(status);
            geliDao.update(userDyna);
        }
        info.setCensored(censored);
        return updateDyna(info, "censored");
    }

    /**
     * 修改动态回复的内容的审核状态
     *
     * @param dynaReplyId
     * @param dynaInfoId
     * @param censored
     * @return
     */
    public long censorDynaReply(DynaReply reply, int censored, DynaInfo dynaInfo) {
        if (reply == null) {
            return 0;
        }
        int oldStatus = reply.getCensored();
        reply.setCensored(censored);
        reply.setStatus(censored == DynaReply.CENSORED_PASS ? DynaReply.STATUS_NORMAL : DynaReply.STATUS_DELETE);
        int count = geliDao.update(reply, "censored,status");
        if (count > 0 && dynaInfo != null) {
            if (oldStatus == DynaReply.CENSORED_PASS && censored == DynaReply.CENSORED_NOTPASS) {
                dynaInfo.setPostCount(Math.max(dynaInfo.getPostCount() - 1, 0));
                updateDyna(dynaInfo, "postCount");
            } else if (oldStatus == DynaReply.CENSORED_NOTPASS && censored == DynaReply.CENSORED_PASS) {
                dynaInfo.setPostCount(Math.max(dynaInfo.getPostCount() + 1, 0));
                updateDyna(dynaInfo, "postCount");
            }
        }
        return count;
    }

    /**
     * 查询某动态的所有图片（最多拿limit张，为0时，表示不限制）
     *
     * @param dynaInfoId
     * @return
     */
    public List<DynaImage> getImagesByDynaInfoId(long dynaInfoId, int limit) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select image_id from ").appendSql(geliOrm.getTableName(DynaImage.class, dynaInfoId));
        sql.appendSql(" where dyna_info_id = ").appendValue(dynaInfoId);
        sql.appendSql(" order by seq asc");
        try {
            if (limit > 0) {
                return geliDao.page(DynaImage.class, dynaInfoId, sql.getSql(), 1, limit, sql.getValues());
            } else {
                return geliDao.list(DynaImage.class, dynaInfoId, sql.getSql(), sql.getValues());
            }
        } catch (EmptyResultDataAccessException e) {
            return Collections.emptyList();
        }
    }

    /**
     *
     * @param dynaInfoId
     * @return
     */
    public long countImagesByDynaInfoId(long dynaInfoId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select count(1) from ").appendSql(geliOrm.getTableName(DynaImage.class, dynaInfoId));
        sql.appendSql(" where dyna_info_id = ").appendValue(dynaInfoId);
        sql.appendSql(" order by seq asc");
        try {
            return geliDao.count(sql.getSql(), sql.getValues());
        } catch (EmptyResultDataAccessException ex) {
            return 0L;
        }
    }

    /**
     * 获取某一车友会动态
     *
     * @param dynaInfoId
     * @param clubId
     * @return
     */
    public ClubDyna findClubDynaById(long dynaInfoId, long clubId) {
        try {
            return geliDao.find(ClubDyna.class, clubId, new Mid(clubId, dynaInfoId));
        } catch (EmptyResultDataAccessException ex) {
            log.info("[clubId,dynaInfoId]({},{})对应的车友会动态不存在", clubId, dynaInfoId);
            return null;
        }
    }

    /**
     * 获取某一同城动态
     *
     * @param dynaInfoId
     * @param clubId
     * @return
     */
    public CityDyna findCityDynaById(long dynaInfoId, long provinceId, long cityId) {
        try {
            return geliDao.find(CityDyna.class, cityId, new Mid(provinceId, cityId, dynaInfoId));
        } catch (EmptyResultDataAccessException ex) {
            if (provinceId == 0 && cityId == 0) {
                return null;///这种数据不应该存在的，不需要打印出日志
            }
            log.info("[provinceId,cityId,dynaInfoId]({},{},{})对应的同城动态不存在", provinceId, cityId, dynaInfoId);
            return null;
        }
    }

    /**
     * 根据id和年份查单条详细动态信息，不包括图片
     *
     * @param id
     * @param createDate
     * @return
     */
    public DynaInfo findDynaInfoById(long id, Date createDate) {
        try {
            return geliDao.find(DynaInfo.class, createDate.getTime(), id);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根据topicId和年份查单条详细动态信息，不包括图片
     *
     * @param id
     * @param createDate
     * @return
     */
    public DynaInfo findDynaInfoByTopicId(long topicId, Date createDate) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select * from ").appendSql(geliOrm.getTableName(DynaInfo.class, createDate.getTime()));
        sql.appendSql(" where topic_id = ").appendValue(topicId);
        return geliDao.findFirst(DynaInfo.class, sql.getSql(), sql.getValues());
    }

    /**
     * 获取某一动态回复
     *
     * @param dynaReplyId
     * @param dynaInfoId
     * @return
     */
    public DynaReply findDynaReplyById(long dynaReplyId, long dynaInfoId) {
        try {
            return geliDao.find(DynaReply.class, dynaInfoId, dynaReplyId);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    /**
     * 根据topicId和发布时间查询动态ID，再进一步根据postId查询对应的回复
     *
     * @param topicId
     * @param topicCreateDate
     * @param postId
     * @return
     */
    public DynaReply findDynaReplyBy(long topicId, Date topicCreateDate, long postId) {
        DynaInfo info = findDynaInfoByTopicId(topicId, topicCreateDate);
        if (info == null) {
            return null;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select * from ").appendSql(geliOrm.getTableName(DynaReply.class, info.getDynaInfoId()));
        sql.appendSql(" where topic_id = ").appendValue(topicId);
        sql.appendSql(" and post_id = ").appendValue(postId);
        return geliDao.findFirst(DynaReply.class, sql.getSql(), sql.getValues());
    }

    /**
     * 根据动态ID分页查询回复列表 descType=0:顺序，1：倒序
     *
     * @param dynaInfoId
     * @param pageNo
     * @param pageSize
     * @return 无查询结果返回NULL
     */
    public Pager<DynaReply> getReplyListByDynaInfoId(long dynaInfoId, int descType, int pageNo, int pageSize) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select dyna_reply_id from ").appendSql(geliOrm.getTableName(DynaReply.class, dynaInfoId));
        sql.appendSql(" where dyna_info_id=").appendValue(dynaInfoId);
        sql.appendSql(" and status != ").appendValue(DynaReply.STATUS_DELETE);
        if (descType == 1) {//倒序
            sql.appendSql(" order by create_date desc");
        }
        if (descType == 0) {//顺序
            sql.appendSql(" order by create_date asc");
        }
        try {
            return pagerService.pager(DynaReply.class, dynaInfoId, sql, pageNo, pageSize);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }
    
    /**
     * 根据回复获取回复的属于第几页
     * @param dynaInfoId
     * @param replyId
     * @param pageSize
     * @return
     */
    public int getReplyPageNo(long dynaInfoId,long replyId,int pageSize){
    	 int count = 1;
    	 SqlBuilder sql = new SqlBuilder();
         sql.appendSql(" select dyna_reply_id from ").appendSql(geliOrm.getTableName(DynaReply.class, dynaInfoId));
         sql.appendSql(" where dyna_info_id=").appendValue(dynaInfoId);
         sql.appendSql(" and status != ").appendValue(DynaReply.STATUS_DELETE);
         sql.appendSql(" order by create_date desc");
         List<Long> idsList = geliDao.getJdbcTemplate().query(sql.getSql(), GeliDao.longIdRowMapper, sql.getValues());
         try {
             if (idsList != null) {
                 for (int i = 0; i < idsList.size(); i++) {
                     if (idsList.get(i) == replyId) {
                         count = i + 1;
                         break;
                     }
                 }
             } else {
                 return 1;
             }
        }
        catch( Exception e ) {
        	return 1;
        }
        return count / pageSize + (count % pageSize == 0 ? 0 : 1);
    }

    /**
     * 根据动态ID分页查询回复列表，默认为倒序
     *
     * @param dynaInfoId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Pager<DynaReply> getReplyListByDynaInfoId(long dynaInfoId, int pageNo, int pageSize) {
        return getReplyListByDynaInfoId(dynaInfoId, 1, pageNo, pageSize);
    }

    /**
     * 根据targetid 获取动态
     *
     * @param createDate	动态创建日期
     * @param targetId
     * @param types	动态类型
     * @return
     */
    public DynaInfo getDynaByTargetId(Date createDate, long targetId, Integer... types) {
        if (targetId <= 0 || types == null || types.length <= 0) {
            return null;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select dyna_info_id from ").appendSql(geliOrm.getTableName(DynaInfo.class, createDate.getTime()));
        sql.appendSql(" where type in ").appendValues(types);
        sql.appendSql(" and target_id = ").appendValue(targetId);
        try {
            List<DynaInfo> list = geliDao.list(DynaInfo.class, createDate.getTime(), sql.getSql(), sql.getValues());
            if (list != null && list.size() > 0) {
                if (list.size() > 1) {
                    log.warn("可能有脏数据！类型 为{}，创建日期为{} 的动态信息存在多个", Arrays.toString(types), createDate.toString());
                }
                return list.get(0);
            }
        } catch (EmptyResultDataAccessException e) {
            log.error("可能有脏数据！类型 为{}，创建日期为{} 的动态信息不存在", Arrays.toString(types), createDate.toString());
        }
        return null;
    }

    /**
     * 获取某一用户动态
     *
     * @param dynaInfoId
     * @param userId
     * @return
     */
    public UserDyna findUserDynaById(long dynaInfoId, long userId) {
        try {
            return geliDao.find(UserDyna.class, userId, new Mid(userId, dynaInfoId));
        } catch (EmptyResultDataAccessException ex) {
            log.error("[userId,dynaInfoId]({},{})对应的用户动态不存在", userId, dynaInfoId);
            return null;
        }
    }

    /**
     * 退出车友会的时候，物理删除车友会动态 注：用户、同城动态不删除 同时dynaInfo的clubId要置0 会物理删除动态的回复
     *
     * @param clubId
     * @param userId
     * @return
     */
    public long deleteClubDynaByUserId(long clubId, long userId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select club_id,dyna_info_id from ").appendSql(geliOrm.getTableName(ClubDyna.class, clubId));
        sql.appendSql(" where club_id = ").appendValue(clubId);
        sql.appendSql(" and create_by = ").appendValue(userId);
        List<ClubDyna> list;
        try {
            list = geliDao.list(ClubDyna.class, clubId, sql.getSql(), sql.getValues());
        } catch (EmptyResultDataAccessException e) {
            return 0;
        }
        long count = 0;
        //String deleteSql = "delete from %s where dyna_info_id = %s";
        for (ClubDyna d : list) {
            DynaInfo info = findDynaInfoById(d.getDynaInfoId(), d.getCreateDate());
            if (info != null) {
                info.setClubId(0);
                updateDyna(info, "club_id");
            }
            d.setStatus(ClubDyna.STATUS_DELETE);
            count += geliDao.delete(d, d.getId());
            //删除回复
            //jdbcTemplate.execute(String.format(deleteSql,
            //  geliOrm.getTableName(DynaReply.class, d.getDynaInfoId()), d.getDynaInfoId()));
            //deleteClubDyna(clubId, d.getDynaInfoId());
        }

        return count;
    }

    /**
     * 帖子删除、审核删除的时候，逻辑删除车友会动态 注：dynaInfo的clubId不需要置0
     *
     * @return
     */
    public long deleteClubDyna(long clubId, long dynaInfoId) {
        ClubDyna dyna = findClubDynaById(dynaInfoId, clubId);
        int countUpdate = 0;
        if (dyna == null) {
            return countUpdate;
        }
        //DynaInfo dynaInfo = findDynaInfoById(dynaInfoId, dyna.getCreateDate());
        //标记删除动态，
        // 删除车友会动态，不要改变基础数据状态
        /*dynaInfo.setStatus(ClubDyna.STATUS_DELETE);
         countUpdate += geliDao.update(dynaInfo, "status");*/
        //标记删除动态车友会索引记录
        dyna.setStatus(ClubDyna.STATUS_DELETE);
        countUpdate += geliDao.update(dyna, "status");
        //动态的回复和动态的图片就不用再标记删除了
        return countUpdate;
    }

    /**
     * 逻辑恢复动态（同时会更新dynaInfo字段的clubId）
     *
     * @return
     */
    public int rollbackClubDyna(long clubId, long dynaInfoId) {
        ClubDyna dyna = findClubDynaById(dynaInfoId, clubId);
        int countUpdate = 0;
        if (dyna == null) {
            return countUpdate;
        }
        //标记恢复动态
        // 删除车友会动态，不要改变基础数据状态
        /*dynaInfo.setStatus(ClubDyna.STATUS_NORMAL);
         countUpdate += geliDao.update(dynaInfo, "status");*/
        //标记恢复动态车友会索引记录
        dyna.setStatus(ClubDyna.STATUS_NORMAL);
        countUpdate += geliDao.update(dyna, "status");
        //动态的回复和动态的图片就不用再标记恢复了
        return countUpdate;
    }

    /**
     * 过滤掉不符合规则的图片
     *
     * @param dynaInfo
     * @return
     */
    public void filterImages(DynaInfo dynaInfo) {
        if (dynaInfo == null) {
            return;
        }
        if (dynaInfo.getImages() != null) {
            dynaInfo.setImages(filterImages(dynaInfo.getImages()));
        }
    }

    /**
     * 过滤掉不符合规则的图片
     *
     * @param dynaInfo
     * @return
     */
    public Pager<DynaInfo> filterImages(Pager<DynaInfo> pager) {
        if (pager == null) {
            return pager;
        }
        if (pager.getResultList() == null || pager.getResultList().isEmpty()) {
            return pager;
        }
        for (DynaInfo info : pager.getResultList()) {
            filterImages(info);
        }
        return pager;
    }

    /**
     * 过滤掉不符合规则的图片
     *
     * @param list
     * @return
     */
    public List<DynaImage> filterImages(List<DynaImage> list) {
        List<DynaImage> rsList = new ArrayList<DynaImage>(list.size());
        for (DynaImage i : list) {
            if (StringUtils.isBlank(i.getUrl())) {
                continue;
            }
            rsList.add(i);
        }
        return rsList;
    }

    /**
     * 根据动态ID查询回复列表，按最新的回复时间排序(不进行分布，用于删除帖子时，更新所有的回复）
     *
     * @param dynaInfoId
     * @return 无查询结果返回NULL
     */
    public List<DynaReply> getAllReplyListByDynaInfoId(long dynaInfoId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select dyna_reply_id from ").appendSql(geliOrm.getTableName(DynaReply.class, dynaInfoId));
        sql.appendSql(" where dyna_info_id=").appendValue(dynaInfoId);
        sql.appendSql(" and status != ").appendValue(DynaReply.STATUS_DELETE);
        sql.appendSql(" order by create_date desc");
        try {
            return geliDao.list(DynaReply.class, sql.getSql(), sql.getValues());
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    /**
     * 查询回复总数
     *
     * @param dynaInfoId
     * @return
     */
    public int countReplyListByDynaInfoId(long dynaInfoId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select count(1) from ").appendSql(geliOrm.getTableName(DynaReply.class, dynaInfoId));
        sql.appendSql(" where dyna_info_id=").appendValue(dynaInfoId);
        sql.appendSql(" and status != ").appendValue(DynaReply.STATUS_DELETE);
        return geliDao.count(sql.getSql(), sql.getValues());
    }

    /**
     * 设置帖子为精华
     *
     * @param topicId
     * @param clubId
     */
    public void setPick(long topicId, Date createDate, int petrol) {
        //更新动态分表
        DynaInfo dynaInfo = findDynaInfoByTopicId(topicId, createDate);
        if (dynaInfo != null && dynaInfo.getPick() == DynaInfo.PICK_NO) {
            dynaInfo.setPick(DynaInfo.PICK_YES);
            dynaInfo.setPetrol(dynaInfo.getPetrol() + petrol);
            updateDyna(dynaInfo, "pick, petrol");
            //更新车友会动态分表
            ClubDyna clubDyna = findClubDynaById(dynaInfo.getDynaInfoId(), dynaInfo.getClubId());
            if (clubDyna != null) {
                clubDyna.setPick(DynaInfo.PICK_YES);
                geliDao.update(clubDyna, "pick");
            }
            //更新品牌车友会动态分表
            List<OClub> oClubs = oClubService.queryClubBy(dynaInfo.getCreateBy(), dynaInfo.getForumId());
            if (oClubs != null && !oClubs.isEmpty()) {
                for (OClub oClub : oClubs) {
                    OClubDyna oClubDyna = oDynaService.findClubDyna(dynaInfo.getDynaInfoId(), oClub.getoClubId());
                    if (oClubDyna != null) {
                        oClubDyna.setPick(DynaInfo.PICK_YES);
                        geliDao.update(oClubDyna, "pick");
                    }
                }
            }
            //更新用户动态分表
            UserDyna userDyna = findUserDynaById(dynaInfo.getDynaInfoId(), dynaInfo.getCreateBy());
            if (userDyna != null) {
                userDyna.setPick(DynaInfo.PICK_YES);
                geliDao.update(userDyna, "pick");
            }
            CityDyna cityDyna = findCityDynaById(dynaInfo.getDynaInfoId(), dynaInfo.getProvinceId(), dynaInfo.getCityId());
            if (cityDyna != null) {
                cityDyna.setPick(DynaInfo.PICK_YES);
                geliDao.update(cityDyna, "pick");
            }
        }
    }

    /**
     * 取消帖子为精华
     *
     * @param topicId
     * @param clubId
     */
    public void removePick(long topicId, Date createDate, int petrol) {
        //更新动态分表
        DynaInfo dynaInfo = findDynaInfoByTopicId(topicId, createDate);
        if (dynaInfo != null && dynaInfo.getPick() == DynaInfo.PICK_YES) {
            dynaInfo.setPick(DynaInfo.PICK_NO);
            int p = dynaInfo.getPetrol() + petrol;
            dynaInfo.setPetrol(p < 0 ? 0 : p);
            updateDyna(dynaInfo, "pick, petrol");
            //更新车友会动态分表
            ClubDyna clubDyna = findClubDynaById(dynaInfo.getDynaInfoId(), dynaInfo.getClubId());
            if (clubDyna != null) {
                clubDyna.setPick(DynaInfo.PICK_NO);
                geliDao.update(clubDyna, "pick");
            }
            //更新品牌车友会动态分表
            List<OClub> oClubs = oClubService.queryClubBy(dynaInfo.getCreateBy(), dynaInfo.getForumId());
            if (oClubs != null && !oClubs.isEmpty()) {
                for (OClub oClub : oClubs) {
                    OClubDyna oClubDyna = oDynaService.findClubDyna(dynaInfo.getDynaInfoId(), oClub.getoClubId());
                    if (oClubDyna != null) {
                        oClubDyna.setRecommend(DynaInfo.PICK_NO);
                        geliDao.update(oClubDyna, "pick");
                    }
                }
            }
            //更新用户动态分表
            UserDyna userDyna = findUserDynaById(dynaInfo.getDynaInfoId(), dynaInfo.getCreateBy());
            if (userDyna != null) {
                userDyna.setPick(DynaInfo.PICK_NO);
                geliDao.update(userDyna, "pick");
            }
            CityDyna cityDyna = findCityDynaById(dynaInfo.getDynaInfoId(), dynaInfo.getProvinceId(), dynaInfo.getCityId());
            if (cityDyna != null) {
                cityDyna.setPick(DynaInfo.PICK_NO);
                geliDao.update(cityDyna, "pick");
            }
        }
    }

    /**
     * 设置帖子为推荐
     *
     * @param topicId
     * @param clubId
     * @param petrol 油值（正数）
     */
    public void setRecommend(long topicId, Date createDate, int petrol) {
        //更新动态分表
        DynaInfo dynaInfo = findDynaInfoByTopicId(topicId, createDate);
        if (dynaInfo != null && dynaInfo.getRecommend() == DynaInfo.RECOMMEND_NO) {
            dynaInfo.setRecommend(DynaInfo.RECOMMEND_YES);
            dynaInfo.setPetrol(dynaInfo.getPetrol() + petrol);
            updateDyna(dynaInfo, "recommend, petrol");
            //更新车友会动态分表
            ClubDyna clubDyna = findClubDynaById(dynaInfo.getDynaInfoId(), dynaInfo.getClubId());
            if (clubDyna != null) {
                clubDyna.setRecommend(DynaInfo.RECOMMEND_YES);
                geliDao.update(clubDyna, "recommend");
            }
            //更新品牌车友会动态分表
            List<OClub> oClubs = oClubService.listClub4Join(dynaInfo.getCreateBy());
            if (oClubs != null && !oClubs.isEmpty()) {
                for (OClub oClub : oClubs) {
                    OClubDyna oClubDyna = oDynaService.findClubDyna(dynaInfo.getDynaInfoId(), oClub.getoClubId());
                    if (oClubDyna != null) {
                        oClubDyna.setRecommend(DynaInfo.RECOMMEND_YES);
                        geliDao.update(oClubDyna, "recommend");
                    }
                }
            }
            //更新用户动态分表
            UserDyna userDyna = findUserDynaById(dynaInfo.getDynaInfoId(), dynaInfo.getCreateBy());
            if (userDyna != null) {
                userDyna.setRecommend(DynaInfo.RECOMMEND_YES);
                geliDao.update(userDyna, "recommend");
            }
            CityDyna cityDyna = findCityDynaById(dynaInfo.getDynaInfoId(), dynaInfo.getProvinceId(), dynaInfo.getCityId());
            if (cityDyna != null) {
                cityDyna.setRecommend(DynaInfo.RECOMMEND_YES);
                geliDao.update(cityDyna, "recommend");
            }
        }
    }

    /**
     * 取消帖子为推荐
     *
     * @param topicId
     * @param clubId
     * @param petrol 油值（负数）
     */
    public void removeRecommend(long topicId, Date createDate, int petrol) {
        //更新动态分表
        DynaInfo dynaInfo = findDynaInfoByTopicId(topicId, createDate);
        if (dynaInfo != null && dynaInfo.getRecommend() == DynaInfo.RECOMMEND_YES) {
            dynaInfo.setRecommend(DynaInfo.RECOMMEND_NO);
            int p = dynaInfo.getPetrol() + petrol;
            dynaInfo.setPetrol(p < 0 ? 0 : p);
            updateDyna(dynaInfo, "recommend, petrol");
            //更新车友会动态分表
            ClubDyna clubDyna = findClubDynaById(dynaInfo.getDynaInfoId(), dynaInfo.getClubId());
            if (clubDyna != null) {
                clubDyna.setRecommend(DynaInfo.RECOMMEND_NO);
                geliDao.update(clubDyna, "recommend");
            }
            //更新品牌车友会动态分表
            List<OClub> oClubs = oClubService.queryClubBy(dynaInfo.getCreateBy(), dynaInfo.getForumId());
            if (oClubs != null && !oClubs.isEmpty()) {
                for (OClub oClub : oClubs) {
                    OClubDyna oClubDyna = oDynaService.findClubDyna(dynaInfo.getDynaInfoId(), oClub.getoClubId());
                    if (oClubDyna != null) {
                        oClubDyna.setRecommend(DynaInfo.RECOMMEND_NO);
                        geliDao.update(oClubDyna, "recommend");
                    }
                }
            }
            //更新用户动态分表
            UserDyna userDyna = findUserDynaById(dynaInfo.getDynaInfoId(), dynaInfo.getCreateBy());
            if (userDyna != null) {
                userDyna.setRecommend(DynaInfo.RECOMMEND_NO);
                geliDao.update(userDyna, "recommend");
            }
            CityDyna cityDyna = findCityDynaById(dynaInfo.getDynaInfoId(), dynaInfo.getProvinceId(), dynaInfo.getCityId());
            if (cityDyna != null) {
                cityDyna.setRecommend(DynaInfo.RECOMMEND_NO);
                geliDao.update(cityDyna, "recommend");
            }
        }
    }

    /**
     * 修改帖子回复内容
     *
     * @param topicId
     * @param createDate
     * @param postId
     * @param content
     */
    public void updateDynaReply(long topicId, Date createDate, long postId, String content) {
        DynaReply dynaReply = findDynaReplyBy(topicId, createDate, postId);
        if (dynaReply == null) {
            return;
        }
        dynaReply.setContent(content);
        geliDao.update(dynaReply, "content");
    }

    /**
     * 恢复帖子回复内容
     *
     * @param topicId
     * @param createDate
     * @param postId
     * @param content
     */
    public void rollbackDynaReply(long topicId, Date createDate, long postId) {
        //更新回复分表状态
        DynaReply dynaReply = findDynaReplyBy(topicId, createDate, postId);
        if (dynaReply == null) {
            return;
        }
        dynaReply.setStatus(DynaReply.STATUS_NORMAL);
        geliDao.update(dynaReply, "status");
        //动态分表postCount + 1
        DynaInfo info = findDynaInfoById(dynaReply.getDynaInfoId(), createDate);
        if (info != null) {
            info.setPostCount(info.getPostCount() + 1);
            //动态用户分表，动态车友会分表postCount + 1
            updateLastReplyInfo(info);
        }
    }

    /**
     * 删除帖子，修改用户动态分表
     *
     * @param userId
     * @param dynaInfoId
     */
    public void deleteUserDyna(long userId, long dynaInfoId) {
        UserDyna userDyna = findUserDynaById(dynaInfoId, userId);
        if (userDyna != null) {
            userDyna.setStatus(UserDyna.STATUS_DELETE);
            geliDao.update(userDyna, "status");
        }
    }

    /**
     * 恢复帖子，修改用户动态分表
     *
     * @param userId
     * @param dynaInfoId
     */
    public int rollbackUserDyna(long userId, long dynaInfoId) {
        UserDyna userDyna = findUserDynaById(dynaInfoId, userId);
        if (userDyna != null) {
            userDyna.setStatus(UserDyna.STATUS_NORMAL);
            return geliDao.update(userDyna, "status");
        }
        return 0;
    }

    /**
     * 恢复帖子，修改城市动态分表
     *
     * @param userId
     * @param dynaInfoId
     */
    public int rollbackCityDyna(long provinceId, long cityId, long dynaInfoId) {
        CityDyna cityDyna = findCityDynaById(dynaInfoId, provinceId, cityId);
        if (cityDyna != null) {
            cityDyna.setStatus(CityDyna.STATUS_NORMAL);
            return geliDao.update(cityDyna, "status");
        }
        return 0;
    }

    /**
     * 删除帖子回复内容
     *
     * @param topicId
     * @param createDate
     * @param postId
     * @param content
     */
    public void deleteDynaReply(long topicId, Date createDate, long postId) {
        //更新回复分表状态
        DynaReply dynaReply = findDynaReplyBy(topicId, createDate, postId);
        if (dynaReply == null) {
            return;
        }
        dynaReply.setStatus(DynaReply.STATUS_DELETE);
        geliDao.update(dynaReply, "status");
        //动态分表postCount - 1
        DynaInfo info = findDynaInfoById(dynaReply.getDynaInfoId(), createDate);
        if (info == null) {
            return;
        }
        info.setPostCount(Math.max(info.getPostCount() - 1, 0));
        //动态用户分表，动态车友会分表postCount - 1
        updateLastReplyInfo(info);
    }

    /**
     * 更新最后回复人相关信息，回复总数加1
     *
     * @param topicId
     * @param coubId
     * @param topicCreateDate
     * @param userId
     * @param postName
     * @param postAt
     * @return
     */
    public boolean updateLastReplyInfoByTopicId(
            long topicId, long coubId, Date topicCreateDate,
            long userId, String postName, Date postAt) {
        DynaInfo info = findDynaInfoByTopicId(topicId, topicCreateDate);
        if (info != null) {
            info.setPostCount(info.getPostCount() + 1);
            info.setLastPostAt(postAt);
            info.setLastPostBy(userId);
            info.setLastPostName(postName);
            return updateLastReplyInfo(info);
        }
        return false;
    }

    /**
     * 发送消息到BIP，针对车友会中的帖子、动态 用于收到被回复的通知
     *
     * @param dynaReply
     * @param createDate
     */
    public void setJson4BipToListReply(DynaReply dynaReply, Date createDate) {
        long dynaId = dynaReply.getDynaInfoId();
        DynaInfo dynaInfo = findDynaInfoById(dynaId, createDate);//动态信息
        DynaReply toDynaReply = findDynaReplyById(dynaReply.getPostToDynaReplyId(), dynaInfo.getDynaInfoId());//被回复的回复信息
        long toReplyId = dynaReply.getPostToDynaReplyId();
        int dynaType = dynaInfo.getType();

        int typeId;
        long senderId = dynaReply.getCreateBy();//发送者即回复人
        long receiverId = dynaReply.getPostToUserId();//接收者即被回复人
        long receiverId2 = dynaInfo.getCreateBy();//接收者即动态创建人
        String dynaUrl = getDynaUrl(dynaInfo);
        if (toReplyId > 0) {//收到回复我的回复
            typeId = systemConfig.getReplyMyReplyType();
            if (senderId != receiverId) {
                JSONObject jsonReply = setJson4Reply(dynaReply, dynaInfo);
                jsonReply.put("url", dynaUrl);
                jsonReply.put("toReplyId", dynaReply.getPostToDynaReplyId());//被回复ID
                jsonReply.put("toReplyContent", toDynaReply == null ? "" : toDynaReply.getContent());//被回复内容
                messageService.send(typeId, senderId, receiverId, jsonReply);//过滤发信息给自己
            }
        } else {
            typeId = systemConfig.getReplyMyDynaType();
        }

        //收到回复我的动态,如果被回复的用户是发动态用户本身，不再发此通知，只发前面回复我的回复的通知
        if (senderId != receiverId2 && receiverId != receiverId2) {
            JSONObject jsonDyna = setJson4Reply(dynaReply, dynaInfo);
            jsonDyna.put("url", dynaUrl);
            jsonDyna.put("toReplyId", dynaId);//动态id
            //为图片动态时，只显示【图】字
            String content = dynaInfo.getContent();
            if (dynaType == DynaInfo.TYPE_PICTURE) {
                content = "";
            } else if (dynaType == DynaInfo.TYPE_CREATE_CLUB) {
                Club club = clubService.getClub(dynaInfo.getClubId());
                String clubName = club == null ? "" : club.getName();
                content = "Hello，我已经加入了" + clubName + "，现在我是一个有组织的人了，欢迎大家来围观！";
            }
            //留言，返回留言内容（带有【图】字）
            jsonDyna.put("toReplyContent", updateDynaContentByImages(dynaId, content));//被回复内容
            messageService.send(typeId, senderId, receiverId2, jsonDyna);//过滤发信息给自己
        }
    }

    /**
     * 发送动态到bip（个人中心使用）
     *
     * @param dynaInfo
     */
    public void sendDynaWithUc(long dynaInfoId, Date createDate) {
        DynaInfo dynaInfo = findDynaInfoById(dynaInfoId, createDate);
        long createBy = dynaInfo.getCreateBy();
        if (createBy == 0) {
            return;
        }
        JSONObject dynaJson = new JSONObject();
        dynaJson = setDynaJSONByDynaType(dynaJson, dynaInfo);
        if (dynaJson != null) {
            int typeId = dynaJson.getIntValue("bipType");
            messageService.sendDyna2BipWithUc(createBy, typeId, dynaJson);
        }

    }

    /**
     * 拼接个动态(仅供发bip使用)
     *
     * @param jsonObject
     * @param dynaInfo
     * @return
     */
    public JSONObject setDynaJSONByDynaType(JSONObject jsonObject, DynaInfo dynaInfo) {
        int dynaType = dynaInfo.getType();
        long clubId = dynaInfo.getClubId();
        Club club = clubService.getValidClub(clubId);
        String content = dynaInfo.getContent();
        List<DynaImage> images = getImagesByDynaInfoId(dynaInfo.getDynaInfoId(), MAX_PICTURE_NUM);
        JSONArray imgsArray = new JSONArray();
        String root = systemConfig.getRoot();
        String ucRoot = systemConfig.getUcRoot();
        String bbsRoot = systemConfig.getBbsRoot();
        String dynaUrl = ucRoot + "/" + dynaInfo.getCreateBy() + "/dt/" + dynaInfo.getDynaInfoId()+"/";
        for (DynaImage img : images) {
            JSONObject imageObject = img.toJSONObject();
            String url;
            if (images.size() > 1) {
                url = img.getUrl120x80();
            } else {
                url = img.getUrl240x160();
            }
            imageObject.put("url", url);
            imgsArray.add(imageObject);
        }

        int bipType = 0;
        long targetId = dynaInfo.getTargetId();
        switch (dynaType) {
            //帖子动态
            case DynaInfo.TYPE_TOPIC:
                bipType = systemConfig.getUcTopicDynaType();
                jsonObject.put("title", EncodeUtils.encodeForHTMLFilterNull(dynaInfo.getTitle()));
                content = WebUtils.transformNoBBSFaceThenLimit(content, 120);
                dynaUrl = bbsRoot + "/topic-" + dynaInfo.getTargetId() + ".html";
                break;
            case DynaInfo.TYPE_QUESTION:
                bipType = systemConfig.getUcQuestionDynaType();
                jsonObject.put("title", EncodeUtils.encodeForHTMLFilterNull(dynaInfo.getTitle()));
                content = WebUtils.transformNoBBSFaceThenLimit(content, 120);
                dynaUrl = bbsRoot + "/topic-" + dynaInfo.getTargetId() + ".html";
                break;
            //说说动态
            case DynaInfo.TYPE_COMMENT:
                bipType = systemConfig.getUcCommentDynaType();
                content = WebUtils.dynaSubjectContent(systemConfig.getRoot(), WebUtils.transformToBBSFace(content), dynaInfo.getSubjectIds());
                break;
            //图片动态
            case DynaInfo.TYPE_PICTURE:
                bipType = systemConfig.getUcPictureDynaType();
                Album album = albumService.getAlbumById(targetId);
                if (album == null) {
                    log.error("dirty data,targetId not correct :[dynaInfo:{}],[clubId:{}],[targetId(albumId):{}]", dynaInfo.getDynaInfoId(), dynaInfo.getClubId(), dynaInfo.getTargetId());
                    return null;
                }
                content = "上传了" + dynaInfo.getPictureNum() + "张相片到" + album.getName();
                break;
            //活动动态
            case DynaInfo.TYPE_ACTIVITY:
                bipType = systemConfig.getUcActivityDynaType();
                Activity a = activityService.findById(targetId);
                if (a == null) {
                    log.error("dirty data,targetId not correct :[dynaInfo:{}],[clubId:{}],[targetId(activityId):{}]", dynaInfo.getDynaInfoId(), dynaInfo.getClubId(), dynaInfo.getTargetId());
                    return null;
                }
                if (club != null) {
                    dynaUrl = root + "/" + club.getClubUrl() + "/activity/a" + dynaInfo.getTargetId() + "/";
                }
                content = a.getTitle();
                if (content.length() > 25) {
                    content = content.substring(0, 25);
                }
                jsonObject.put("joinCount", a.getJoinNum());
                break;
            case DynaInfo.TYPE_VOTE:
                bipType = systemConfig.getUcVoteDynaType();
                Vote vote = voteService.findVoteByVoteId(dynaInfo.getTargetId());
                if (vote == null) {
                    log.error("dirty data,targetId not correct :[dynaInfo:{}],[clubId:{}],[targetId(voteId):{}]", dynaInfo.getDynaInfoId(), dynaInfo.getClubId(), dynaInfo.getTargetId());
                    return null;
                }
                content = vote.getVoteTitle();
                jsonObject.put("voteCount", vote.getVoteCount());
                break;
            case DynaInfo.TYPE_CREATE_CLUB:
                bipType = systemConfig.getUcCreateClubDynaType();
                break;
            case DynaInfo.TYPE_JOIN_CLUB:
                bipType = systemConfig.getUcJoinClubDynaType();
                break;
            case DynaInfo.TYPE_NOTICE:
                bipType = systemConfig.getUcNoticeDynaType();
                break;
        }
        jsonObject.put("bipType", bipType);
        jsonObject.put("targetId", targetId);
        jsonObject.put("infoLink", dynaUrl);
        if (club != null) {
            jsonObject.put("clubName", club.getName());
            jsonObject.put("clubUrl", root + "/" + club.getClubUrl());
        }
        jsonObject.put("summary", content);

        jsonObject.put("images", imgsArray);
        jsonObject.put("createAt", DateUtils.format(dynaInfo.getCreateAt(), "MM-dd HH:mm:ss"));
        jsonObject.put("avatar", WebUtils.face(dynaInfo.getCreateBy(), DEFAULT_AUTHORPHOTO_SIZE));
        jsonObject.put("nickName", userService.findUser(dynaInfo.getCreateBy()).getNickname());
        jsonObject.put("accountUrl", ucRoot + "/" + dynaInfo.getCreateBy());
        return jsonObject;
    }

    /**
     * 获取动态的终端（帖子页，动态终端页，活动终端页）
     *
     * @param dynaInfo
     * @return
     */
    private String getDynaUrl(DynaInfo dynaInfo) {
        if (dynaInfo.getTopicId() > 0) {
            return systemConfig.getBbsRoot() + "/topic-" + dynaInfo.getTopicId() + ".html";
        }
        long clubId = dynaInfo.getClubId();
        Club club = clubService.getValidClub(clubId);
        if (club == null) {
            return "";
        }
        if (dynaInfo.getType() != DynaInfo.TYPE_ACTIVITY) {
            return systemConfig.getUcRoot() + "/" + dynaInfo.getCreateBy() + "/dt/" + dynaInfo.getDynaInfoId() + "/";
        }
        if (dynaInfo.getType() == DynaInfo.TYPE_ACTIVITY) {
            return systemConfig.getRoot() + "/" + club.getClubUrl() + "/activity/a" + dynaInfo.getTargetId() + "/";
        }
        return "";
    }

    /**
     * 发送车友会动态消息（只是生成发送名单）
     *
     * @param dynaInfo
     */
    public void sendClubDynaMsg(DynaInfo dynaInfo) {
        JSONObject json = new JSONObject();
        json.put("type", dynaInfo.getType()); //动态类型
        json.put("dynaInfoId", dynaInfo.getDynaInfoId());//动态ID
        json.put("userId", dynaInfo.getCreateBy());
        json.put("createDate", dynaInfo.getCreateDate());
        json.put("clubId", dynaInfo.getClubId());
        json.put("content", getPushDynaContent(dynaInfo.getCreateBy(), dynaInfo));
        String content = json.toJSONString();
        sendMsgService.createClubDynaMsg(dynaInfo.getCreateBy(), dynaInfo.getClubId(), content);
    }

    /**
     * 发送消息到BIP，针对没有同步到车友会的帖子 用于收到被回复的通知
     *
     * @param postReply
     */
    public void setJson4BipBbsTopics(PostReply postReply) {
        boolean isQuote = postReply.isIsQuote();//是否引用，即回复别人的回复
        int typeId;
        long senderId = postReply.getUserId();//发送者即回复人
        long receiverId = postReply.getPostToUserId();//接收者即被回复人
        long receiverId2 = postReply.getTopicUserId();//接收者即帖子创建人

        long topicId = postReply.getTopicId();  //帖子id
        Date createAt = postReply.getTopicCreateAt();
        DynaInfo dynaInfo = findDynaInfoByTopicId(topicId, createAt);
        if (isQuote) {//收到回复我的回复
            typeId = systemConfig.getReplyMyReplyType();
            if (senderId != receiverId) {
                JSONObject jsonReply = setJson4Topic(postReply);
                if (dynaInfo != null) {
                    jsonReply.put("fid", dynaInfo.getForumId());
                }
                jsonReply.put("toReplyId", postReply.getPostToPostId());//被回复ID
                jsonReply.put("toReplyContent", postReply.getPostToMessage());//被回复内容
                messageService.send(typeId, senderId, receiverId, jsonReply);//过滤发信息给自己
            }
        } else {
            typeId = systemConfig.getReplyMyDynaType();
        }
        //收到回复我的帖子,如果被回复的用户是发帖子用户本身，不再发此通知，只发前面回复我的回复的通知
        if (senderId != receiverId2 && receiverId != receiverId2) {
            JSONObject jsonTopic = setJson4Topic(postReply);
            if (dynaInfo != null) {
                jsonTopic.put("fid", dynaInfo.getForumId());
            }
            jsonTopic.put("toReplyId", postReply.getTopicId());//被回复帖子ID
            jsonTopic.put("toReplyContent", postReply.getTopicTitle());//被回复帖子Title
            messageService.send(typeId, senderId, receiverId2, jsonTopic);//过滤发信息给自己
        }
    }

    /**
     * 组装动态回复的Json内容，针对车友会中的帖子、动态
     *
     * @param dynaReply
     * @param dynaInfo
     * @return
     */
    public JSONObject setJson4Reply(DynaReply dynaReply, DynaInfo dynaInfo) {
        JSONObject json = new JSONObject();
        int type = dynaInfo.getType();
        json.put("replyType", type); //动态类型,1:帖子，2：动态
        json.put("targetId", dynaInfo.isTopic() ? dynaInfo.getTopicId() : dynaInfo.getDynaInfoId());//帖子ID 或者动态ID 或者活动id
        json.put("dynaInfoId", dynaInfo.getDynaInfoId());	//动态id
        json.put("dynaTargetId", getDynaTargetId(dynaInfo)); //targetid
        json.put("replyId", dynaReply.getDynaReplyId());//回复ID
        json.put("replyContent", dynaReply.getContent());//回复内容
        json.put("replyUserId", dynaReply.getCreateBy());//回复人ID
        json.put("replyUserName", userService.getNickNameByUserId(dynaReply.getCreateBy()));//回复人昵称
        json.put("replyUserImg", WebUtils.face(dynaReply.getCreateBy(), DEFAULT_AUTHORPHOTO_SIZE));//回复人头像
        json.put("time", dynaReply.getCreateAt());
        json.put("createBy", dynaInfo.getCreateBy());//动态创建者ID
        return json;
    }

    private long getDynaTargetId(DynaInfo dynaInfo) {
        if (dynaInfo.isTopic()) {
            return dynaInfo.getTopicId();
        }
        if (dynaInfo.getType() == DynaInfo.TYPE_ACTIVITY || dynaInfo.getType() == DynaInfo.TYPE_VOTE) {
            return dynaInfo.getTargetId();
        }
        return dynaInfo.getDynaInfoId();
    }

    /**
     * 组装帖子回复的Json内容，针对没有同步到车友的帖子
     *
     * @param postReply
     * @return
     */
    public JSONObject setJson4Topic(PostReply postReply) {
        JSONObject json = new JSONObject();
        //发消息时，都当作是帖子消息，不用区分普通帖子还是提问帖子
        json.put("replyType", DynaInfo.TYPE_TOPIC); //只针对帖子》1:帖子
        json.put("targetId", postReply.getTopicId());//帖子ID
        json.put("replyId", postReply.getPostId());//回复ID
        json.put("replyContent", postReply.getMessage());//回复内容
        json.put("replyUserId", postReply.getUserId());//回复人ID
        json.put("replyUserName", userService.getNickNameByUserId(postReply.getUserId()));//回复人昵称
        json.put("replyUserImg", WebUtils.face(postReply.getUserId(), DEFAULT_AUTHORPHOTO_SIZE));//回复人头像
        json.put("time", postReply.getCreateAt());
        json.put("createBy", postReply.getTopicUserId());//帖子创建者ID
        return json;
    }

    /**
     * 根据动态ID查找动态图片，并根据图片个数据，在动态内容后面增加相应的【图】字
     *
     * @param dynaInfoId动态ID
     * @param content动态内容
     * @return追加【图】字后的动态内容
     */
    public String updateDynaContentByImages(long dynaInfoId, String content) {
        StringBuilder sb = new StringBuilder();
        sb.append(content);
        long total = countImagesByDynaInfoId(dynaInfoId);
        for (int i = 0; i < total && i <= MAX_PICTURE_NUM; i++) {//相册上传的会超过9张，这里最多9个图字，跟以前保持一致
            sb.append("[图]");
        }
        return sb.toString();
    }

    public DynaPraise findDynaPraise(long userId, long dynaInfoId) {
        try {
            return geliDao.find(DynaPraise.class, dynaInfoId, new Mid(userId, dynaInfoId));
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }
    /**
     * 批量查询点赞列表(只查已赞)
     * @param userId
     * @param list
     * @return 
     */
    public List<DynaPraise> listDynaPraise(long userId,List<Long> list){
        List<DynaPraise> praises = new ArrayList<DynaPraise>();
        Map<Integer,List<Long>> map = new HashMap<Integer,List<Long>>();
        for(long dynaInfoId : list){
            int tableNameIndex = (int) dynaInfoId %10;
            List<Long> ids = map.get(tableNameIndex);
            if(ids == null){
                ids = new ArrayList<Long>();
            }
            ids.add(dynaInfoId);
            map.put(tableNameIndex, ids);
        }
        for(Integer index : map.keySet()){
            SqlBuilder sql = new SqlBuilder();
             sql.appendSql("select user_id,dynainfo_id from ").appendSql(geliOrm.getTableName(DynaPraise.class, index)).appendSql(" where user_id=").appendValue(userId)
                     .appendSql(" and status = ").appendValue(DynaPraise.STATUS_PRAISE)
                     .appendSql(" and dynainfo_id in ").appendValues(map.get(index).toArray());
             praises.addAll(geliDao.list(DynaPraise.class, index,sql.getSql(),sql.getValues()));
        }
        return praises;
    }
    public UserPraise findUserPraise(long userId, long dynaInfoId, long dynainfoCreateBy) {
        try {
            return geliDao.find(UserPraise.class, dynainfoCreateBy, new Mid(userId, dynaInfoId));
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    private void increasePraiseCount(long dynaInfoId, Date date) {
        StringBuilder sql = new StringBuilder();
        sql.append("update ").append(geliOrm.getTableName(DynaInfo.class, date.getTime()));
        sql.append(" set praise_count = praise_count + 1 ");
        sql.append(" where dyna_info_id = ").append(dynaInfoId);
        geliDao.getJdbcTemplate().execute(sql.toString());
        deleteDynaCache(dynaInfoId);
    }

    private void decreasePraiseCount(long dynaInfoId, Date date) {
        StringBuilder sql = new StringBuilder();
        sql.append("update ").append(geliOrm.getTableName(DynaInfo.class, date.getTime()));
        sql.append(" set praise_count = praise_count - 1 ");
        sql.append(" where dyna_info_id = ").append(dynaInfoId);
        geliDao.getJdbcTemplate().execute(sql.toString());
        deleteDynaCache(dynaInfoId);
    }

    /**
     * 点赞/取消点赞
     *
     * @param userId
     * @param dynaInfoId
     * @param createDate
     * @return
     */
    public boolean doPraise(long userId, long dynaInfoId, Date createDate, int status) {
        DynaInfo dynaInfo = findDynaInfoById(dynaInfoId, createDate);
        if (dynaInfo == null) {
            return false;
        }
        DynaPraise p = findDynaPraise(userId, dynaInfoId);
        if (p == null) {
            if (status == DynaPraise.STATUS_UNPRAISE) {//没记录不能取消赞
                return false;
            }
            //创建动态点赞表记录
            DynaPraise dp = new DynaPraise();
            dp.setDynainfoCreateBy(dynaInfo.getCreateBy());
            dp.setDynainfoCreateAt(dynaInfo.getCreateDate());
            dp.setDynainfoId(dynaInfo.getDynaInfoId());
            //创建用户点赞表记录
            UserPraise userPraise = new UserPraise();
            userPraise.setDynainfoCreateBy(dynaInfo.getCreateBy());
            userPraise.setDynainfoCreateAt(dynaInfo.getCreateDate());
            userPraise.setDynainfoId(dynaInfo.getDynaInfoId());
            userPraise.setPraiseTime(new Date());
            userPraise.setStatus(DynaPraise.STATUS_PRAISE);//点赞
            userPraise.setUserId(userId);
            //动态用户给自己点赞，标志为已读
            if (dynaInfo.getCreateBy() != userId) {
                dp.setIsRead(DynaPraise.READ_NO);
                userPraise.setIsRead(DynaPraise.READ_NO);
            } else {
                dp.setIsRead(DynaPraise.READ_YES);
                userPraise.setIsRead(DynaPraise.READ_YES);
            }
            dp.setPraiseTime(new Date());
            dp.setStatus(DynaPraise.STATUS_PRAISE);//点赞
            dp.setUserId(userId);
            geliDao.create(dp);
            geliDao.create(userPraise);
            //点赞 计数+1
            increasePraiseCount(dynaInfo.getDynaInfoId(), dynaInfo.getCreateDate());
            return true;
        } else {
            if (p.getStatus() == status) {//状态没变化不操作
                return true;
            }
            if (status == DynaPraise.STATUS_UNPRAISE) {//取消赞
                decreasePraiseCount(dynaInfo.getDynaInfoId(), dynaInfo.getCreateDate());
            } else {//点赞
                increasePraiseCount(dynaInfo.getDynaInfoId(), dynaInfo.getCreateDate());
            }
            Date now = new Date();
            p.setStatus(status);
            p.setPraiseTime(now);
            UserPraise up = findUserPraise(userId, dynaInfoId, dynaInfo.getCreateBy());
            up.setStatus(status);
            up.setPraiseTime(now);
            return geliDao.update(p, "status,praise_time") > 0 && geliDao.update(up, "status,praise_time") > 0;
        }
    }

    /**
     * 收到的赞列表(不包括自赞的）
     *
     * @param dynainfoCreateBy
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Pager<UserPraise> getPraiseList(long dynainfoCreateBy, int pageNo, int pageSize) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select user_id,dynainfo_id from ").appendSql(geliOrm.getTableName(UserPraise.class, dynainfoCreateBy)).appendSql(" where dynainfo_create_by = ").appendValue(dynainfoCreateBy);
        sql.appendSql(" and user_id <> ").appendValue(dynainfoCreateBy);
        sql.appendSql(" order by praise_time desc");
        return pagerService.pager(UserPraise.class, dynainfoCreateBy, sql, pageNo, pageSize);
    }

    /**
     * 未读点赞清零，返回操作成功的ID
     *
     * @param dynainfoCreateBy
     * @param dynainfoIds
     */
    public List<Long> clearUnreadPraise(long dynainfoCreateBy, List<Long> dynainfoIds) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select user_id,dynainfo_id from ").appendSql(geliOrm.getTableName(UserPraise.class, dynainfoCreateBy)).appendSql(" where dynainfo_create_by = ").appendValue(dynainfoCreateBy);
        if (!dynainfoIds.isEmpty()) {
            sql.appendSql(" and dynainfo_id in ").appendValues(dynainfoIds.toArray());
        }
        sql.appendSql(" and is_read = ").appendValue(DynaPraise.READ_NO);
        sql.appendSql(" and status = ").appendValue(DynaPraise.STATUS_PRAISE);
        try {
            List<UserPraise> list = geliDao.list(UserPraise.class, dynainfoCreateBy, sql.getSql(), sql.getValues());
            List<Long> rs = new ArrayList<Long>();
            for (UserPraise si : list) {
                //              si = geliDao.find(UserPraise.class, new Mid(si.getUserId(), si.getDynainfoId()));
                if (si.getIsRead() == DynaPraise.READ_YES) {
                    rs.add(si.getDynainfoId());
                    continue;
                }
                si.setIsRead(DynaPraise.READ_YES);
                if (geliDao.update(si, "is_read") > 0) {
                    //update用户点赞表之后再update动态点赞表
                    DynaPraise dynaPraise = findDynaPraise(si.getUserId(), si.getDynainfoId());
                    if (dynaPraise.getIsRead() == DynaPraise.READ_NO) {
                        dynaPraise.setIsRead(DynaPraise.READ_YES);
                        geliDao.update(dynaPraise, "is_read");
                    }
                    rs.add(si.getDynainfoId());
                }
            }
            return rs;
        } catch (EmptyResultDataAccessException e) {
            return Collections.emptyList();
        }
    }

    /**
     * 根据动态ID获取点赞的用户列表，按时间倒序排序
     *
     * @param dynaInfoId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Pager<User> getPraiseUserList(long dynaInfoId, int pageNo, int pageSize) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select user_id from ").appendSql(geliOrm.getTableName(DynaPraise.class, dynaInfoId)).appendSql(" where dynainfo_id = ").appendValue(dynaInfoId);
        sql.appendSql(" and status = ").appendValue(DynaPraise.STATUS_PRAISE);
        sql.appendSql(" order by praise_time desc");
        return pagerService.pager(User.class, sql, pageNo, pageSize);
    }

    /**
     * 用于判断是否已赞
     *
     * @param userId
     * @param dynaInfoIds
     * @return
     */
    public List<DynaPraise> getPraiseList(long userId, List<DynaInfo> dynaInfoList) {
        if(userId == 0 ){
            return Collections.EMPTY_LIST;
        }
        //批量查询点赞列表
        List<Long> idList = new ArrayList<Long>();
        for(DynaInfo dynaInfo : dynaInfoList){
            idList.add(dynaInfo.getDynaInfoId());
        }
        List<DynaPraise> list =listDynaPraise(userId, idList);
        return list;
    }

    /**
     * 未读已赞数
     *
     * @param dynaInfoIdCreateBy
     * @return
     */
    public int getUnReadCount(long dynaInfoIdCreateBy) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select count(1) from ").appendSql(geliOrm.getTableName(UserPraise.class, dynaInfoIdCreateBy)).appendSql(" where dynainfo_create_by = ").appendValue(dynaInfoIdCreateBy);
        sql.appendSql(" and user_id <> ").appendValue(dynaInfoIdCreateBy);
        sql.appendSql(" and status = ").appendValue(DynaPraise.STATUS_PRAISE);
        sql.appendSql(" and is_read = ").appendValue(DynaPraise.READ_NO);
        return geliDao.count(sql.getSql(), sql.getValues());
    }

    /**
     * 已赞数列表
     *
     * @param dynaInfoIdCreateBy
     * @return
     */
    public List<DynaPraise> getUnReadList(long dynaInfoIdCreateBy) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select user_id,dynainfo_id from ").appendSql(geliOrm.getTableName(UserPraise.class, dynaInfoIdCreateBy)).appendSql(" where dynainfo_create_by = ").appendValue(dynaInfoIdCreateBy);
        sql.appendSql(" and status = ").appendValue(DynaPraise.STATUS_PRAISE);
        sql.appendSql(" and user_id <> ").appendValue(dynaInfoIdCreateBy);
        sql.appendSql(" order by praise_time desc");
        try {
            return geliDao.list(DynaPraise.class, sql.getSql(), sql.getValues());
        } catch (EmptyResultDataAccessException exception) {
            return Collections.emptyList();
        }
    }

    /**
     * 获得帖子/动态 进行推送的文案
     *
     * @param createBy
     * @param dynaInfo
     * @return
     */
    public String getPushDynaContent(long createBy, DynaInfo dynaInfo) {
        if (createBy <= 0 || dynaInfo == null) {
            return "";
        }
        String content = "";
        content += userService.getNickNameByUserId(dynaInfo.getCreateBy()) + ":";
        if (dynaInfo.getType() == DynaInfo.TYPE_TOPIC) {
            content += "发表了新的帖子";
        } else {
            content += "分享了新的动态";
        }
        return content;
    }

    /**
     * 发布投票时发布动态
     *
     * @param dyna
     * @param images
     * @return
     */
    public long createVoteDyna(AbstractDyna dyna, List<DynaImage> images) {
        return createAbstractDyna(dyna, DynaInfo.TYPE_VOTE, images);
    }

    /**
     * 创建动态（公告|活动|加入车友会|图片|创建车友会）不创建同城索引
     *
     * @param picture
     * @param images 如果没有图片就传空的
     * @return
     */
    private long createAbstractDyna(AbstractDyna dyna, int type, List<DynaImage> images) {
        DynaInfo info = new DynaInfo();
        info.setCensored(DynaInfo.CENSORED_UNDO);
        info.setClubId(dyna.getClubId());
        info.setContent(dyna.getContent());
        info.setCreateDate(dyna.getCreateDate());
        info.setCreateName(dyna.getCreateName());
        //第一次发表留言动态，上次回复人是自己
        info.setLastPostAt(dyna.getCreateDate());
        info.setLastPostBy(dyna.getCreateBy());
        info.setLastPostName(dyna.getCreateName());
        //设置相关联ID
        info.setTargetId(dyna.getTargetId());
        info.setPostCount(0);
        info.setUpdateAt(dyna.getCreateDate());
        boolean hasPic = (images != null && !images.isEmpty());
        info.setIsPic(hasPic ? DynaInfo.PIC_IS : DynaInfo.PIC_NOT);
        info.setStatus(DynaInfo.STATUS_NORMAL);
        info.setType(type);
        info.setCreateBy(dyna.getCreateBy());
        info.setProvinceId(0);
        info.setCityId(0);
        long infoId = geliDao.create(info);
        if (infoId == 0) {
            log.error("插入动态记录失败！createAbstractDyna[type={}]", type);
            return infoId;
        }
        if (hasPic) {
            for (DynaImage image : images) {
                image.setDynaInfoId(infoId);
                geliDao.create(image);
            }
        }
        if (dyna.getClubId() > 0) {
            //创建车友会动态索引
            createClubDyna(info);
            sendClubDynaMsg(info);
        }
        //创建用户动态索引
        createUserDyna(info);
        //添加动态索引
        dynaIndexService.createDynaIndex(info);

        //发送动态到bip（个人中心使用）
        sendDynaWithUc(infoId, dyna.getCreateDate());
        return infoId;
    }

    /**
     * 图片动态
     *
     * @param dyna
     * @param images
     * @return
     */
    public long createPictureDyna(AbstractDyna dyna, List<DynaImage> images) {
        return createAbstractDyna(dyna, DynaInfo.TYPE_PICTURE, images);
    }

    /**
     * 活动动态
     *
     * @param dyna
     * @param images
     * @return
     */
    public long createActivityDyna(AbstractDyna dyna, List<DynaImage> images) {
        return createAbstractDyna(dyna, DynaInfo.TYPE_ACTIVITY, images);
    }

    /**
     * 参加活动动态
     *
     * @param dyna
     * @param images
     * @return
     */
    public long createJoinActivityDyna(AbstractDyna dyna) {
        //APP展示活动相关的动态的时候，不需要封面图片
        return createAbstractDyna(dyna, DynaInfo.TYPE_JOIN_ACTIVITY, null);
    }

    /**
     * 创建车友会时发布的动态
     *
     * @param dyna
     * @param images
     * @return
     */
    public long createCreateClubDyna(AbstractDyna dyna, List<DynaImage> images) {
        return createAbstractDyna(dyna, DynaInfo.TYPE_CREATE_CLUB, images);
    }

    /**
     * 加入车友会时发布的动态
     *
     * @param dyna
     * @param images
     * @return
     */
    public long createJoinClubDyna(AbstractDyna dyna, List<DynaImage> images) {
        return createAbstractDyna(dyna, DynaInfo.TYPE_JOIN_CLUB, images);
    }

    /**
     * 发布公告时发布的动态
     *
     * @param dyna
     * @param images
     * @return
     */
    public long createNoticeDyna(AbstractDyna dyna, List<DynaImage> images) {
        return createAbstractDyna(dyna, DynaInfo.TYPE_NOTICE, images);
    }

    /**
     * 获取置顶数量
     *
     * @return
     */
    public int getTopCount(long clubId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select count(1) from ").appendSql(geliOrm.getTableName(ClubDyna.class, clubId));
        sql.appendSql(" where is_top = ").appendValue(ClubDyna.TOP_YES).appendSql(" and club_id = ").appendValue(clubId);
        sql.appendSql(" and status !=").appendValue(ClubDyna.STATUS_DELETE);
        return geliDao.count(sql.getSql(), sql.getValues());
    }

    /**
     * 动态置顶
     *
     * @param dynaInfoId
     * @param clubId
     * @return
     */
    public boolean doTop(long dynaInfoId, long clubId) {
        ClubDyna clubDyna = findClubDynaById(dynaInfoId, clubId);
        if (clubDyna != null) {
            if (clubDyna.getIsTop() != ClubDyna.TOP_YES) {
                clubDyna.setIsTop(ClubDyna.TOP_YES);
                clubDyna.setTopDate(new Date());
                return geliDao.update(clubDyna, "is_top,top_date") > 0;
            }
            return true;
        }
        return false;

    }

    /**
     * 取消置顶
     *
     * @param dynaInfoId
     * @param clubId
     * @return
     */
    public boolean cancelTop(long dynaInfoId, long clubId) {
        ClubDyna clubDyna = findClubDynaById(dynaInfoId, clubId);
        if (clubDyna != null) {
            if (clubDyna.getIsTop() != ClubDyna.TOP_NO) {
                clubDyna.setIsTop(ClubDyna.TOP_NO);
                clubDyna.setTopDate(null);
                return geliDao.update(clubDyna, "is_top,top_date") > 0;
            }
            return true;
        }
        return false;

    }

    public void deleteCityDyna(long dynaInfoId, long provinceId, long cityId) {
        CityDyna cityDyna = findCityDynaById(dynaInfoId, provinceId, cityId);
        if (cityDyna != null) {
            cityDyna.setStatus(CityDyna.STATUS_DELETE);
            geliDao.update(cityDyna, "status");
        }
    }

    /**
     * 根据动态类型，动态目标ID，和年份查单条详细动态信息，不包括图片
     *
     * @param type
     * @param targetId
     * @param createDate
     * @return
     */
    public DynaInfo findDynaByTypeTargetId(int type, long targetId, Date createDate) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select * from ").appendSql(geliOrm.getTableName(DynaInfo.class, createDate.getTime()));
        sql.appendSql(" where 1 = 1 ");
        if (type > 0) {
            sql.appendSql(" and type = ").appendValue(type);
        }
        if (targetId > 0) {
            sql.appendSql(" and target_Id = ").appendValue(targetId);
        }
        return geliDao.findFirst(DynaInfo.class, sql.getSql(), sql.getValues());
    }

    /**
     * 用户是否点赞过ID为dynaInfoId的动态
     *
     * @param dynaInfoId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public int getPraseCountByUid(long dynaInfoId, long uid) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select count(1) from ").appendSql(geliOrm.getTableName(DynaPraise.class, dynaInfoId)).appendSql(" where dynainfo_id = ").appendValue(dynaInfoId);
        sql.appendSql(" and user_id =").appendValue(uid);
        sql.appendSql(" and status = ").appendValue(DynaPraise.STATUS_PRAISE);
        return geliDao.count(sql.getSql(), sql.getValues());
    }

    public int countDynaNumByType(long clubId, int... type) {
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.appendSql("select count(1) from ");
        sqlBuilder.appendSql(geliDao.getTableName(ClubDyna.class, clubId));
        sqlBuilder.appendSql(" where club_id = ").appendValue(clubId);
        sqlBuilder.appendSql(" and status = ").appendValue(1);
        if (type != null) {
            if (type.length == 1) {
                sqlBuilder.appendSql(" and type = ").appendValue(type[0]);
            } else if (type.length > 1) {
                Object[] types = Arrays.asList(type).toArray();
                sqlBuilder.appendSql(" and type in ").appendValues(types);
            }
        }
        return geliDao.count(sqlBuilder.getSql(), sqlBuilder.getValues());
    }

    public Pager<DynaInfo> searchDyna(Date from, Date to, String keyword, AbstractDyna.DynaOrder order, int pageNo, int pageSize, Integer... types) {
        if (from == null && to == null) {
            return null;
        }
        Calendar fromCal = Calendar.getInstance();
        if (from != null) {
            fromCal.setTime(from);
        }
        fromCal.add(Calendar.HOUR_OF_DAY, 0);
        fromCal.add(Calendar.MINUTE, 0);
        fromCal.add(Calendar.SECOND, 0);
        fromCal.add(Calendar.MILLISECOND, 0);
        Calendar toCal = Calendar.getInstance();
        if (to != null) {
            toCal.setTime(to);
        }
        toCal.add(Calendar.HOUR_OF_DAY, 23);
        toCal.add(Calendar.MINUTE, 59);
        toCal.add(Calendar.SECOND, 59);
        toCal.add(Calendar.MILLISECOND, 999);

        int fromYear = fromCal.get(Calendar.YEAR);
        int toYear = toCal.get(Calendar.YEAR);
        if (toYear != fromYear) {//不同一年，会跨表，不支持
            return null;
        }
        //select dyna_info_id from ac_dyna_info_2015 where type = 2 and create_date > '2015-01-11' 
        //and content like '%情人%' order by praise_count desc,post_count desc
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.appendSql("select dyna_info_id from ");
        sqlBuilder.appendSql(geliDao.getTableName(DynaInfo.class, fromCal.getTimeInMillis()));

        sqlBuilder.appendSql(" where club_id > ").appendValue(0);
        sqlBuilder.appendSql(" and create_date >= ").appendValue(fromCal.getTime());
        sqlBuilder.appendSql(" and create_date <= ").appendValue(toCal.getTime());

        if (StringUtils.isNotBlank(keyword)) {
            sqlBuilder.appendSql(" and content like ").appendValue("%" + keyword + "%");
        }

        if (types != null && types.length > 0) {
            if (types.length == 1) {
                sqlBuilder.appendSql(" and type = ").appendValue(types[0]);
            } else {
                sqlBuilder.appendSql(" and type in ").appendValues(Arrays.asList(types).toArray());
            }
        }

        if (order != null) {
            if (AbstractDyna.DynaOrder.PRAISE_COUNT.equals(order)) {
                sqlBuilder.appendSql(" order by praise_count");
            } else if (AbstractDyna.DynaOrder.PRAISE_COUNT_DESC.equals(order)) {
                sqlBuilder.appendSql(" order by praise_count desc");
            } else if (AbstractDyna.DynaOrder.POST_COUNT.equals(order)) {
                sqlBuilder.appendSql(" order by post_count");
            } else if (AbstractDyna.DynaOrder.POST_COUNT_DESC.equals(order)) {
                sqlBuilder.appendSql(" order by post_count desc");
            }
        } else {
            sqlBuilder.appendSql(" order by create_date desc");
        }
        log.info("sql: {}\nparams: {}", sqlBuilder.getSql(), Arrays.toString(sqlBuilder.getValues()));
        //return geliDao.list(DynaInfo.class, fromCal.getTimeInMillis(), sqlBuilder.getSql(), sqlBuilder.getValues());
        return pagerService.pager(DynaInfo.class, fromCal.getTimeInMillis(), sqlBuilder, pageNo, pageSize);
    }

    public Map<Long, Integer> getDynaPraise(Date from, Date to, Long... dynaIds) {
        if (from == null && to == null) {
            return null;
        }
        Calendar fromCal = Calendar.getInstance();
        if (from != null) {
            fromCal.setTime(from);
        }
        fromCal.add(Calendar.HOUR_OF_DAY, 0);
        fromCal.add(Calendar.MINUTE, 0);
        fromCal.add(Calendar.SECOND, 0);
        fromCal.add(Calendar.MILLISECOND, 0);

        Calendar toCal = Calendar.getInstance();
        if (to != null) {
            toCal.setTime(to);
        }
        toCal.add(Calendar.HOUR_OF_DAY, 23);
        toCal.add(Calendar.MINUTE, 59);
        toCal.add(Calendar.SECOND, 59);
        toCal.add(Calendar.MILLISECOND, 999);

        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.appendSql("select dynainfo_id,count(1) cnt from ac_dyna_praise where 1=1");  
        if (dynaIds != null && dynaIds.length > 0) {
                sqlBuilder.appendSql(" and dynainfo_id in ").appendValues(Arrays.asList(dynaIds).toArray());
        }
        sqlBuilder.appendSql(" and praise_time >= ").appendValue(fromCal.getTime());
        sqlBuilder.appendSql(" and praise_time <= ").appendValue(toCal.getTime());
        sqlBuilder.appendSql(" group by dynainfo_id");
        log.info("sql: {}\nparams: {}, {}", sqlBuilder.getSql(), Arrays.toString(sqlBuilder.getValues()), Arrays.toString(Arrays.asList(dynaIds).toArray()));
        try {
            return jdbcTemplate.query(sqlBuilder.getSql(), new ResultSetExtractor<Map<Long, Integer>>() {
                Map<Long, Integer> result = new HashMap<Long, Integer>();

                @Override
                public Map<Long, Integer> extractData(ResultSet rs) throws SQLException, DataAccessException {
                    while (rs.next()) {
                        result.put(rs.getLong("dynainfo_id"), rs.getInt("cnt"));
                    }
                    return result;
                }
            }, sqlBuilder.getValues());
        } catch (EmptyResultDataAccessException e) {
            //e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建官方车友会动态索引
     *
     * @param dynaInfo
     */
    public void createOClubDyna(DynaInfo dynaInfo) {
        if (dynaInfo == null) {
            return;
        }
        long createBy = dynaInfo.getCreateBy();
        if (createBy > 0) {
            List<OClub> oClubs = oClubService.queryClubBy(createBy, dynaInfo.getForumId());
            User user = userService.findUser(createBy);
            if (user != null) {
                if (oClubs != null && !oClubs.isEmpty()) {
                    for (OClub oClub : oClubs) {
                        //当品牌车友会需要绑定手机,且用户没有绑定手机时不同步帖子
                        if (oClub.isMustBindPhone() && StringUtils.isBlank(user.getBindPhone())) {
                            continue;
                        }
                        //用户被车友会封锁时不同步
                        if (!oMemberService.isUserLock(user, oClub.getoClubId())) {
                            oDynaService.createClubDyna(dynaInfo, oClub.getoClubId());
                        }
                    }
                }
            }
        }
    }
    /**
     * 根据说说内容，创建或参与话题
     *
     * @param content
     * @param dynaInfoId
     * @param commentDyna
     */
    private static final String INTRODUCE = "欢迎大家参与讨论！";

    public String createSubjectByDyna(DynaInfo info) {
        //进行话题匹配
        Pattern p = Pattern.compile(Regex.subjectRule.value);
        Matcher matcher = p.matcher(info.getContent());
        List<String> subjectList = new ArrayList<String>();
        while (matcher.find()) {
            subjectList.add(matcher.group(1));
        }

        //一条说说会参与的话题ID
        String subjectIds = "";
        //对匹配的说说创建话题
        for (String subjectTitle : subjectList) {
            subjectTitle = "#" + subjectTitle.trim() + "#";
            //话题已经存在，参与话题
            Subject subject = subjectService.findByTitle(subjectTitle);
            if (subject != null) {
                //是否一个说说提供同一个话题
                SubjectDyna subjectDyna = subjectDynaService.findSubjectDynaById(subject.getSubjectId(), info.getDynaInfoId());
                if (subjectDyna == null) {
                    subject.setReplyCount(subject.getReplyCount() + 1);
                    //更新话题评论数
                    geliDao.update(subject, "reply_count");
                    subject.setCreateBy(info.getCreateBy());
                    //创建话题-用户记录
                    userSubjectService.createUserSubject(subject, info.getDynaInfoId(), Subject.TOP_NO);
                    //创建话题-动态记录
                    subjectDynaService.createDynaSubject(subject, info.getDynaInfoId(), Subject.TOP_NO);
                }
                //一条说说会参与的话题ID
                subjectIds = subjectIds + subject.getSubjectId() + ",";

            } else {//创建新话题
                Subject subjectNew = new Subject();
                subjectNew.setTitle(subjectTitle);
                subjectNew.setCreateAt(info.getCreateDate());
                subjectNew.setCreateBy(info.getCreateBy());
                subjectNew.setPvCount(0);
                subjectNew.setReplyCount(1);
                subjectNew.setStatus(Subject.STATUS_NORMAL);
                subjectNew.setUpdateAt(info.getCreateDate());
                subjectNew.setUpdateBy(info.getCreateBy());
                //subjectNew.setCover(cover);
                subjectNew.setIntroduction(INTRODUCE);
                //subjectNew.setLogo(logo);
                subjectService.createSubject(subjectNew, info.getDynaInfoId());
                //一条说说会参与的话题ID
                subjectIds = subjectIds + subjectNew.getSubjectId() + ",";
            }
        }

        return subjectIds;
    }

    /**
     * 获取WAP版动态图片规则
     *
     * @param images
     * @return
     */
    public JSONArray parseWapImagesJSON(List<DynaImage> images) {
        JSONArray array = new JSONArray();
        if (images != null && !images.isEmpty()) {
            for (DynaImage image : images) {
                JSONObject imgObj = new JSONObject();
                int len = images.size();
                if (len <= 9 && len > 1) {
                    imgObj.put("width", 74);
                    imgObj.put("height", 74);
                    imgObj.put("smaPic", WebUtils.transPicUrl(image.getUrl500x500(), 150, 150));
                    imgObj.put("bigPic", image.getUrl400x400());
                } else {
                    float width = image.getWidth();
                    float height = image.getHeight();
                    if (width > height) {
                        if (height < 90) {
                            if (width > 300) {
                                height = 90;
                                width = 300;
                            } else {
                                height = height / (width / 300);
                                width = 300;
                            }
                        } else {
                            height = height / (width / 300);
                            width = 300;
                        }
                    } else if (height > width) {
                        if (width < 90) {
                            if (height > 300) {
                                height = 90;
                                width = 300;
                            } else {
                                width = width / (height / 300);
                                height = 300;
                            }
                        } else {
                            width = width / (height / 300);
                            height = 300;
                        }
                    } else if (width == height) {
                        height = 300;
                        width = 300;
                    }
                    imgObj.put("width", (int) width / 2);
                    imgObj.put("height", (int) height / 2);
                    imgObj.put("smaPic", WebUtils.transPicUrl(image.getUrl500x500(), (int) width, (int) height));
                    imgObj.put("bigPic", image.getUrl400x400());
                }
                array.add(imgObj);
            }
        }
        return array;
    }
}
